import uuid

from dao.DBUtil import getDB
from model.TodoDto import TodoDto


class TodoDao(object):

    def insertTodo(self, date, content, complete):
        conn = getDB()

        sql = 'insert into todo_table(id, date, content, complete) values (?, ?, ?, ?)'
        cursor = conn.cursor()
        cursor.execute(sql, (str(uuid.uuid4()), date, content, complete))
        conn.commit()
        cursor.close()
        conn.close()

    def queryTodo(self, date):
        conn = getDB()
        sql = 'select * from todo_table where date = ?'
        cursor = conn.cursor()
        cursor.execute(sql, (date,))

        result = []
        for item in cursor.fetchall():
            print(item)
            todoDto = TodoDto(item[0], item[1], item[2], item[3])
            result.append(todoDto)

        cursor.close()
        conn.close()
        return result

    def updateTodo(self, id_key, contentDict):
        conn = getDB()

        conditonList = []
        values = []

        sql = 'update todo_table set '
        for key, value in contentDict.items():
            condi = key + "=?"
            conditonList.append(condi)
            values.append(value)
        values.append(id_key)

        sql = sql + ",".join(values) + " where id=?"

        cursor = conn.cursor()
        cursor.execute(sql, tuple(values))

        conn.commit()
        cursor.close()
        conn.close()

    def deleteTodo(self, id_key):
        conn = getDB()
        sql = 'delete from todo_table where id=?'

        cursor = conn.cursor()
        cursor.execute(sql, (id_key,))

        conn.commit()
        cursor.close()
        conn.close()


if __name__ == '__main__':
    todoDao = TodoDao()
    todoDao.insertTodo('2021-1-21', '测试得')
    print(todoDao.queryTodo('2021-1-21'))
